package hhq;

import bean.*;
import com.alibaba.fastjson.*;

import java.io.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/index")
public class serv extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static ConDB condb;

    public serv() {
        super();
        condb = new ConDB();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Tools.setEnc(request, response);

        JSONObject jb = Tools.getJson(request);

        String ac = jb.getString("ac");
        switch (ac) {
            case "login":
                login(request, response, jb);
                break;
            case "reLogin":
                reLogin(request, response);
                break;
            case "register":
                register(request, response, jb);
                break;
            case "liuyan":
                liuyan(request, response, jb);
                break;
            case "get_new":
                get_new(request, response, jb);
                break;
            case "remove":
                remove(request, response, jb);
                break;
        }
    }

    private void remove(HttpServletRequest req,
            HttpServletResponse res,
            JSONObject jb) throws IOException {
        PrintWriter out = res.getWriter();
        Record r = jb.getObject("data", Record.class);
        if (condb.del_liuyan(r)) {
            out.print("{\"code\":200 ,\"mess\": \"删除成功 \"}");
        } else {
            out.print("{\"code\":400 , \"mess\": \"删除失败  或者mysql未链接 \"}");
        }
        out.close();
    }

    private void login(HttpServletRequest req,
            HttpServletResponse res,
            JSONObject jb) throws IOException {
        PrintWriter out = res.getWriter();
        User u = jb.getObject("user", User.class);

        if (condb.login_user(u)) {
            out.print("{\"code\":200 ,\"mess\": \"登陆成功 \"}");
            req.getSession().setAttribute("user", u);
        } else {
            out.print("{\"code\":400 , \"mess\": \"用户名或密码不正确 或者mysql未链接 \"}");
        }
        out.close();
    }

    private void reLogin(HttpServletRequest req,
            HttpServletResponse res) throws IOException {
        User user = (User) req.getSession().getAttribute("user");
        PrintWriter out = res.getWriter();
        if (user != null) {
            out.print("{\"code\":200, \"name\":\"" + user.getName() + "\" }");
        } else {
            out.print("{\"code\":400, \"mess\":\"reLogin error 或者mysql未链接 \" }");
        }
        out.close();
    }

    private void register(HttpServletRequest req,
            HttpServletResponse res,
            JSONObject jb) throws IOException {
        PrintWriter out = res.getWriter();
        User u = jb.getObject("user", User.class);
        if (condb.insert_user(u)) {
            out.print("{\"code\":200 ,\"mess\": \"注册成功 \"}");
            req.getSession().setAttribute("user", u);
        } else {
            out.print("{\"code\":400 , \"mess\": \"注册失败  或者mysql未链接 \"}");
        }
        out.close();
    }

    // insert record; liuyan
    private void liuyan(HttpServletRequest req,
            HttpServletResponse res,
            JSONObject jb) throws IOException {
        PrintWriter out = res.getWriter();
        Record r = jb.getObject("record", Record.class);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
        r.setTim(df.format(new Date()));
        if (condb.insert_liuyan(r)) {
            out.print("{\"code\":200 ,\"mess\": \"留言成功 \"}");
        } else {
            out.print("{\"code\":400 , \"mess\": \"留言失败 或者mysql未链接 \"}");
        }
        out.close();
    }

    // get all record; see liuyan;
    private void get_new(HttpServletRequest req,
            HttpServletResponse res,
            JSONObject jb) throws IOException {
        PrintWriter out = res.getWriter();
        JSONArray arr = condb.see_liuyan();
        JSONObject ob1 = new JSONObject();

        if (arr.isEmpty()) {
            ob1.put("code", 500);
            ob1.put("mess", "失败：无法获取任何数据，或者mysql未链接 ");
            ob1.put("data", arr);
        } else {
            ob1.put("code", 200);
            ob1.put("mess", "刷新成功");
            ob1.put("data", arr);
        }
        String string = ob1.toJSONString();
        out.print(string); // 返回jSON
        out.close();
    }

}

class Tools {
    public static JSONObject getJson(HttpServletRequest request) throws IOException, UnsupportedEncodingException {
        // 读取请求内容
        BufferedReader br = new BufferedReader(
                new InputStreamReader(request.getInputStream(), "utf-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        // 将json字符串转换为json对象
        // System.out.println(sb.toString());
        JSONObject jb = JSONObject.parseObject(sb.toString());
        return jb;
    }

    public static void setEnc(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
